package com.hhdys.action;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Producer;
import com.hhdys.annotation.Access;
import com.hhdys.util.Constant;

@Controller
@RequestMapping("/admin/common")
@Access("基础设置")
public class CommonAction {
	private Producer captchaProducer = null;

	@Autowired
	public void setCaptchaProducer(Producer captchaProducer) {
		this.captchaProducer = captchaProducer;
	}

	@RequestMapping("/captcha")
	public void handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Subject curUser=SecurityUtils.getSubject();
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");

		response.setContentType("image/jpeg");

		String capText = captchaProducer.createText();
		curUser.getSession().setAttribute(Constant.KAPTCHA_SESSION_KEY,capText);

		BufferedImage bi = captchaProducer.createImage(capText);

		ServletOutputStream out = response.getOutputStream();

		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
	}
	@RequestMapping("captchaSwitch")
	@ResponseBody
	public String  catchaSwitch() {
		if(Constant.KAPTCHASWITCH){
			return "true";
		}
		return "false";
	}
	@RequestMapping("/settings")
	@Access("查看")
	public String commonSet(Model model){
		model.addAttribute("kaptcha",Constant.KAPTCHASWITCH);
		return "admin/webset/commonSet";
	}
	@RequestMapping("/changeCatcha")
	@Access("修改")
	@ResponseBody
	public void changeCatchaSwitch(boolean state){
		if(state){
			Constant.KAPTCHASWITCH=true;
		}else {
			Constant.KAPTCHASWITCH=false;
		}
	}
}
